<?php

declare(strict_types=1);

namespace App\Job;

use App\Core\Log;
use App\Model\Area;
use App\Model\PaperQuestion;
use App\Model\PointPosition;
use App\Model\UserPaperAnswer;
use App\Repositories\CommunityRepository;
use App\Repositories\StreetRepository;
use App\Repositories\UserPaperAnswerRepository;
use App\Repositories\UserRepository;
use Hyperf\AsyncQueue\Job;

class InputQuestionJob extends Job
{
    public $params;

    protected $maxAttempts = 2;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        Log::get('queue')->info('InputQuestionJob开始执行',$this->params);
        $header_data=[
            'ID',
            '问卷id',
            '用户昵称',
            '所属区县',
            '所属街道',
            '实践站名称',
            '文本答题详情'
        ];
        $start_time = isset($this->params['start_time'])?$this->params['start_time']:'';
        $end_time = isset($this->params['end_time'])?$this->params['end_time']:'';
        $paper_id = isset($this->params['paper_id'])?$this->params['paper_id']:0;
        $file = $this->params['file_url'];
        $folder = BASE_PATH.'/public'.$file;
        $fp = fopen($folder,'w+');
        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'GBK', $value);
            }
            fputcsv($fp, $header_data);
        }
        $query = UserPaperAnswer::query()->orderBy('user_paper_answer.id','desc')
            ->where('question_type',PaperQuestion::TYPE_INPUT)
            ->join('user_paper',function($join){
                $join->on('user_paper_answer.user_paper_id','=','user_paper.id')
                    ->whereNull('user_paper.deleted_at');
            });
        if($start_time!=''&&$end_time!=''){
            $query->where('user_paper_answer.created_at','>=',$start_time)
                ->where('user_paper_answer.created_at','<=',$end_time);
        }
        //if($paper_id){
        $query->where('user_paper_answer.paper_id',$paper_id);
        //}
        $query_count = clone $query;
        $all = $query_count->count('user_paper_answer.id');
        if($all==0){
            cache()->set('export_'.$this->params['hash_id'],100);
            return false;
        }
        $columns=[
            'user_paper_id',
            'user_paper.paper_id',
            'user_paper_answer.id',
            'answer_txt',
            'district_id',
            'street_id',
            'community_id',
            'user_id'
        ];
        $start_count=0;
        $street_ids=[];
        $community_ids = [];
        $districts = Area::query()->where('parent_id',223)->get()->keyBy('id')->toArray();
        $query->select($columns)->chunk(300,function($answers) use($fp,$all,&$start_count,&$street_ids,&$community_ids,&$districts){
            foreach ($answers as $item){
                $user= UserRepository::getInstance()->getBaseInfo($item['user_id']);
                $district = isset($districts[$item['district_id']])?$districts[$item['district_id']]:null;
                if($item['street_id']){
                    if(isset($street_ids[$item['street_id']])){
                        $street = $street_ids[$item['street_id']];
                    }else{
                        $street = StreetRepository::getInstance()->one(['id','name'],[[
                            'field' => 'id',
                            'value' => $item['street_id']
                        ]]);
                        $street_ids[$item['street_id']] = $street;
                    }
                }
                if($item['community_id']){
                    if(isset($community_ids[$item['community_id']])){
                        $community= $community_ids[$item['community_id']];
                    }else{
                        $community = CommunityRepository::getInstance()->one(['id','name'],[[
                            'field' => 'id',
                            'value' => $item['community_id']
                        ]]);
                        $community_ids[$item['community_id']] = $community;
                    }
                }
                //$row[0] = $user->mobile.' ';
                $row[0] = $item->id.' ';
                $row[1] = $item->user_paper_id.' ';
                $row[2] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$user->wechat->wx_nickname);
                $row[3] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$district['name']);
                $row[4] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($street,'name','暂无'));
                $row[5] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($community,'name','暂无'));
                $row[6] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$item->answer_txt);
                fputcsv($fp,$row);
            }
            $start_count+=300;
            $progress = $start_count>=$all?1:sprintf('%.2f',$start_count/$all);
            cache()->set('export_'.$this->params['hash_id'],$progress*100);

        });
    }
}
